import { Inject, Injectable } from '@nestjs/common';
import { CreateUserDto } from './dto/create-user.dto';
import { UpdateUserDto } from './dto/update-user.dto';
import { InjectRepository } from '@nestjs/typeorm';
import { User } from "./entities/user.entity";
import { Repository } from 'typeorm';
import { PaginationQueryDto } from "../common/dto/pagination-query.dto";
import * as bcrypt from 'bcrypt';
import { JwtService } from '@nestjs/jwt';

/**
 */
@Injectable()
export class UsersService {
  constructor(
    @InjectRepository(User)
    private readonly userRepository: Repository<User>,
    private readonly jwtService: JwtService,
  ) { }

  async create(createUserDto: CreateUserDto) {
    try {
      // 检查用户是否已存在
      const existUser = await this.userRepository.findOneBy({
        phone: createUserDto.phone
      });
      if (existUser) {
        //判断密码对不对
        const isPasswordMatching = await bcrypt.compare(createUserDto.password, existUser.password);
        if (!isPasswordMatching) {
          return "密码错误"
        } else {
          // 密码正确，生成token
          const token = this.jwtService.sign({
            id: existUser.id,
            phone: existUser.phone
          });

          // 返回用户信息和token（不包含密码）
          const { password, ...rest } = existUser;
          return {
            ...rest,
            token
          };
        }

      }

      // 创建用户实例
      const user = this.userRepository.create(createUserDto);

      // 密码加密
      const salt = await bcrypt.genSalt();
      user.password = await bcrypt.hash(user.password, salt);

      // 保存用户并返回结果（不包含密码）
      const result = await this.userRepository.save(user);
      // 生成 token（这里使用 result 而不是 existUser）
      const token = this.jwtService.sign({
        id: result.id,
        phone: result.phone
      });
      // 返回结果时排除密码字段
      const { password, ...rest } = result;
      return {
        ...rest,
        token
      };

    } catch (error) {
    }
  }

  async findAll(paginationQuery: PaginationQueryDto) {
    const { limit, page } = paginationQuery;
    const total = await this.userRepository.count();
    const users = await this.userRepository.find({
      select: ['id', 'username', 'phone', 'createTime'],
      skip: limit * (page - 1),
      take: limit,
    });
    return {
      total,
      page,
      limit,
      users
    }
  }

  async findOne(id: number) {
    try {
      const user = await this.userRepository.findOneBy({ id });
      return user;
    } catch (error) {
    }
  }

  async update(updateUserDto: UpdateUserDto, authToken: string) {
    try {
      const decodedToken = this.jwtService.verify(authToken);

      // 查找用户
      const user = await this.userRepository.findOneBy({ id: decodedToken.id });
      if (!user) {
        return "用户不存在"
      }
      // 更新用户信息
      await this.userRepository.update(decodedToken.id, updateUserDto);
      return '更新成功';

    } catch (error) {
      console.log('update error:', error);  // 添加日志
      return "更新1用户失败"
    }
  }

  remove(id: number) {
    return `This action removes a #${id} user`;
  }
}
